package com.sk.places.places2.business.service;
//http://forum.springsource.org/showthread.php?115349-Autowired-issue
import java.net.URL;
import java.util.Date;
import java.util.List;
import java.util.logging.Logger;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.json.JSONObject;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.sk.places.places2.service.entity.UserInfo;
import com.visural.common.IOUtil;
@Repository
@Transactional(readOnly=true) 
public class UserServiceImpl implements UserService {

	private Logger logger = Logger.getLogger(getClass().getName()) ;
	@PersistenceContext(name="PlacesService" )
	private EntityManager em ; 

	//private UserPersistentService userPersistentService ; 
//	@Autowired(required=true)
//	private UserRepository userRepository; 
	
	
    public UserInfo getFacebookUser(String accessToken, int expires) {
    	String firstName = null ; 
        try {
        	UserInfo ui = new UserInfo() ; 
            JSONObject resp = new JSONObject(
                IOUtil.urlToString(new URL("https://graph.facebook.com/me?access_token=" + accessToken)));
            //String id = resp.getString("id");
            firstName = resp.getString("first_name");
            String lastName = resp.getString("last_name");
            String email = resp.getString("email");

            logger.info(" first name " + firstName + " lastname " + lastName) ;
            // ...
            // create and authorise the user in your current system w/ data above
            // ...
            ui.setEmail(email) ;
            ui.setFirstName(firstName) ;
            ui.setLastName(lastName) ; 
            ui = save(ui) ;
            return ui ; 

        } catch (Throwable ex) {
            //throw new RuntimeException("failed login", ex);
        	logger.severe(" error occurred while persisting " + ex.getMessage()) ;
        	return createGuestUser() ; 
        }
    }

    private UserInfo createGuestUser()  { 
    	UserInfo guestUi = new UserInfo() ;
    	guestUi.setFirstName("Guest") ;
    	guestUi.setLastName("") ; 
    	return guestUi ; 
    }

    @Override
    @Transactional 
    public UserInfo save(UserInfo ui) {
    	try {
    		String firstName = ui.getFirstName() ;
    		String lastName = ui.getLastName() ; 
    		ui.setDatevisited(new Date()) ; 
    		UserInfo uiDB = findByEmail(ui.getEmail()) ;
    		UserInfo uiNew  = null; 
    		if(uiDB== null) {
    			 em.persist(ui) ;
    			 uiNew = em.merge(ui) ;
    		}
    		else {
    			ui.setId(uiDB.getId()) ; 
    			uiNew= update(ui);
    		}
    		if(uiNew != null) { 
	   			 uiNew.setFirstName(firstName) ; 
	   			 uiNew.setLastName(lastName) ;
	   			 return uiNew ; 
    			
    		} 
    		else { 
    			return ui ; 
    		}
    			
    	}
    	catch(Exception e) {
    		e.printStackTrace(); 
    		logger.severe("error occurred " + e.getMessage()) ;
    		return ui; 
    	}
    }
    
	public EntityManager getEm() {
		return em;
	}


	public UserInfo findByEmail(String email) {
		logger.info(" email is " + email) ; 
		Query qry = em.createQuery("select ui from UserInfo ui where email = ?");
		qry.setParameter(1, email) ; 
		List<UserInfo> data = qry.getResultList() ;
		if(data == null || data.size() < 1) {
			logger.info(" no user found with id " + email + " , returnng null ") ; 
			return null;
		}
		else  {
			logger.info(" User found with id " + email  ) ;
			return data.get(0) ; 
		}
		
	}

	public UserInfo update(UserInfo ui) { 
		return em.merge(ui) ;
	}
	
	public void setEm(EntityManager em) {
		this.em = em;
	}



}